#include "fun.h"

u8 bdata com;
sbit BUZZER = com^6;
sbit RELAY = com^4;

u8 key_value = 0;
u8 key_up = 1;

void buzzer(u8 cmd)
{
	BUZZER = cmd;
	P0 = com;
	P2 = 0xa0;
	_nop_();
	P2 = 0x00;
}

void relay(u8 cmd)
{
	RELAY = cmd;
	P0 = com;
	P2 = 0xa0;
	_nop_();
	P2 = 0x00;
}

void led(u8 ucode)
{
	P0 = ~ucode;
	P2 = 0x80;
	_nop_();
	P2 = 0x00;
}

void key_scan(void)
{
	u8 flag = 0;
	if(key_up)
	{
		P44 = 0;P42 = 1;
		P35 = 1;P34 = 1;
		if((P3 & 0x0C) != 0x0C)
			flag = 1;
		else
		{
			P44 = 1;P42 = 0;
			if((P3 & 0x0C) != 0x0C)
				flag = 2;
			else
			{
				P42 = 1;P35 = 0;
				if((P3 & 0x0C) != 0x0C)
					flag = 3;
				else
				{
					P35 = 1;P34 = 0;
					if((P3 & 0x0C) != 0x0C)
						flag = 4;
					else
						flag = 0;
				}
			}
		}
		
		if(flag)
		{
			key_up = 0;
			if(!P33)
				key_value = flag * 4;
			else if(!P32)
				key_value = (flag * 4) + 1;
		}
	}
	else
	{
		if((P3 & 0x0C) == 0x0C)
			key_up = 1;
	}
}
	
void smg_disp(u8 num,u8 position)
{
	P0 = 0xff;
	P2 = 0xe0;
	_nop_();
	P2 = 0x00;
	
	P0 = position;
	P2 = 0xc0;
	_nop_();
	P2 = 0x00;
	
	P0 = ~num;
	P2 = 0xe0;
	_nop_();
	P2 = 0x00;
}

u8 get_dis(void)
{
	u8 count = 8;
	TF0 = 0;
	TL0 = 0xF4;		
	TH0 = 0xFF;	
	TR0 = 1;
	while(count--)
	{
		P10 = ~P10;
		while(!TF0);
		TF0 = 0;
	}
	TR0 = 0;
	TL0 = 0;
	TH0 = 0;
	TR0 = 1;
	while((!TF0)&&P11);
	TR0 = 0;
	if(TF0)
	{
		TF0 = 0;
		return 99;
	}
	else
	{
		if((((TH0<<8) | TL0) * 0.017) > 99)
			return 99;
		else
			return ((TH0<<8) | TL0) * 0.017;
	}
}	
